import React from 'react';
import { inject, observer } from "mobx-react";
import { Icon, Row, Tooltip } from 'antd'
import { WeaTools,WeaLocaleProvider,WeaBrowser,WeaUpload} from 'ecCom'
import {toJS} from 'mobx';
import NewLinkeb from '../../../public/newlinked/NewLinkeb';
import * as Util from "../../../util/Util";
const getLabel = WeaLocaleProvider.getLabel;
@inject("goalDetailStore","goalCommonStore")
@observer
export default class GoalRelateInfo extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            ...props,
        }
        this.relateTop=[
            {icon:'icon-portal-ModelingEngine',type:'wrlgoal',key:'relateGoals',name:getLabel(330,'目标'),fieldname:'goalids'},
            {icon:'icon-coms-currency-Task',type:'wrltsk',key:'relateTasks',name:getLabel(1332,'任务'),fieldname:'taskids'},
            {icon:'icon-portal-doc',type:'9',key:'relateDocs',name:getLabel(22243,'文档'),fieldname:'docids'},
            {icon:'icon-coms-Workflow-o',type:'152',key:'relateWorkFlows',name:getLabel(18015,'流程'),fieldname:'wfids'},
            {icon:'icon-portal-crm',type:'7',key:'relateCutomer',name:getLabel(136,'客户'),fieldname:'crmids'},
            {icon:'icon-coms-project',type:'8',key:'relateProjects',name:getLabel(101,'项目'),fieldname:'projectids'},
        ],
        this.mirror = {
            37: "/spa/document/index.jsp?id=",
            7: "/spa/crm/static/index.html#/main/crm/customerView?customerId=",
            152: "/workflow/request/ViewRequestForwardSPA.jsp?requestid=",
            8: "/spa/prj/index.html#/main/prj/projectCard?prjid=",
            1:'/spa/hrm/index_mobx.html#/main/hrm/card/cardInfo/',
            // "wrlgoal":'/spa/workrelate/static/index.html?#/main/workrelate/goal/goalDetail?id=',
            "wrltask":'/spa/workrelate/static/index.html?#/main/workrelate/task/taskDetail?id='
        }
    }
    componentWillMount(){
        WeaTools.callApi('/api/workrelate/common/getRelateURL', 'GET').then((data) => {
            if (data.status) {
                this.mirror[7] = data.result[7];
            }
        
        })
    }
    
    componentDidMount(){
        const { goalDetailStore } = this.props;
        goalDetailStore.loading = false;
    }

    //附件上传
    getUpload = () => {
        const { goalDetailStore} = this.props;
        const {category,maxUploadSize} = goalDetailStore;
        if(goalDetailStore.flag){
            return <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@3pkt2o`}
                    ref = 'upload'
                    uploadUrl={'/api/doc/upload/uploadFile2Doc?category=' + category}
                    category={category} maxUploadSize={maxUploadSize} viewAttr={2}
                    onChange={(ids, list) =>this.uploadChange(ids,list)}
                    // maxFilesNumber = {1}
                    onUploading={(status) => 
                        this.uploading(status)
                        }
                    >
                    <span>{getLabel(156,'附件')}</span>
                </WeaUpload>
        }else{
            return <span>{getLabel(156,'附件')}</span>
        }
    }

    //上传状态
    uploading = (status) =>{
        const { goalDetailStore } = this.props;
        if(status == 'uploading'){
            goalDetailStore.loading = true;
        }else{
            goalDetailStore.loading = false;
        }
    }

    //上传附件
    uploadChange = (ids, list) => {
        const { goalDetailStore } = this.props;
        goalDetailStore.loading = true;
        if (ids.length > 0) {
            let newAddFileids = '';
            for (let i = 0; i < list.length; i++) {
                let fileA = {};
                if (goalDetailStore.detailData.fileids.indexOf(',' + ids[i] + ',') == -1) {
                    newAddFileids += ids[i] + ',';
                    if(goalDetailStore.detailData.fileids == ''){
                        goalDetailStore.detailData.fileids += ","
                    }
                    goalDetailStore.detailData.fileids += ids[i] + ',';
                    fileA.id = ids[i];
                    fileA.name = list[i].filename;
                    fileA.size = list[i].filesize;
                    fileA.fileid = list[i].imagefileid;
                    goalDetailStore.detailData.relateFileds.push(fileA);
                }
            }
            let params = {
                goalId:goalDetailStore.detailKey,
                fieldname:'',  //字段名字
                fieldtype:'',  //类型
                fieldvalue:'',  //字段值
                logDelvalue:'', //日志删除值
                logAddValue:'', //日志增加值
                operateType:'', //操作类型
            };
            params.fieldname = 'fileids';
            params.fieldvalue = newAddFileids
            if (newAddFileids.length > 0) {
                goalDetailStore.editGoalField(params);
            }
        }
    }

    //相关信息头部
    getRelateTopInfo(datas){
        const {goalDetailStore:{detailData},goalCommonStore:{condtype}} = this.props;
        return datas && datas.length>0 && datas.map((element,idx)=>{
            if(element.type == "wrlgoal"){
                return <div className="relate-info-link">
                {(!detailData.canedit && !Util.isEmpty(detailData.canedit)) ? <div><i className={element.icon} /><div class="wea-browser customized wea-field-readonly "><div><span class="relate-info-link-span">{element.name}</span></div></div></div> : <div><i className={element.icon}/>
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@itr38y@${element.fieldname}`} title={element.name} icon={element.icon} type={element.type} replaceDatas={toJS(detailData[element.key])} onChange={(ids, names, datas) => this.browserChange(element.key,ids,names,datas,element.fieldname)} isSingle={false} customized memorise={true} dataParams={{ condtype}} completeParams={{ condtype }}><span>{element.name}</span></WeaBrowser></div>}
                </div>;
            }else{
                return <div className="relate-info-link">
                {(!detailData.canedit && !Util.isEmpty(detailData.canedit)) ? <div><i className={element.icon} /><div class="wea-browser customized wea-field-readonly "><div><span class="relate-info-link-span">{element.name}</span></div></div></div> : <div><i className={element.icon}/>
                <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@itr38y@${element.fieldname}`} title={element.name} icon={element.icon} type={element.type} replaceDatas={toJS(detailData[element.key])} onChange={(ids, names, datas) => this.browserChange(element.key,ids,names,datas,element.fieldname)} isSingle={false} customized memorise={true}><span>{element.name}</span></WeaBrowser></div>}
                </div>;
            }

        });
    }
    //相关信息展示
    getRelateShowInfo(datas,t){
        let {goalDetailStore:{detailData},goalCommonStore:{iconArray}} = this.props;
        if(t == 1){  //相关信息
            return datas && datas.length>0 && datas.map((element,idx)=>{
                return <div className={(element.datas && element.datas.length > 0)?"relate-info-type":"relate-ishidden  relate-info-type"}>
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@6nwmxu@${element.fieldname}`} title={getLabel(522,'相关')+element.name}><div className="relate-info-type-div"><i className={iconArray[element.fieldname]} /></div></Tooltip> 
                            <NewLinkeb ecId={`${this && this.props && this.props.ecId || ''}_NewLinkeb@9i8p4v@${element.fieldname}`} _width='20' linkurl={this.mirror[element.type]} onLinkClick={(id,name,type,fileid) => this.onLinkClick(id,name,type,fileid,element.fieldname,element.key)} linkdatas={element.datas} hasdel={detailData.canedit} hasdownload={element.fieldname && element.fieldname == 'fileids'?true:false} />
                        </div>
            });
        }else{  //被关联的相关信息
            return datas && datas.length>0 && datas.map((element,idx)=>{
                return  <div className={(element.datas && element.datas.length > 0)?"relate-info-type":" relate-ishidden relate-info-type"}>
                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@ebfh6k@${element.fieldname}`} title={getLabel(508805,'关联了此目标的${word}').replace('${word}',element.name)}><div className="relate-info-type-div"><i className={iconArray[element.fieldname]} style={{color:"red"}}/></div></Tooltip> 
                            <NewLinkeb ecId={`${this && this.props && this.props.ecId || ''}_NewLinkeb@jmgzye@${element.fieldname}`} _width='20' linkurl={this.mirror[element.type]} onLinkClick={(id,name,type,fileid) => this.onLinkClick(id,name,type,fileid,element.fieldname,element.key)} linkdatas={element.datas} hasdel={detailData.canedit} />
                        </div>
            });
        }
    }

    //更新浏览按钮  参与人  负责人  分享人 ,上级目标
    browserChange = (type,ids, names, datas,fieldname) => {
        const { goalDetailStore } = this.props;
        const {detailData,detailKey} = goalDetailStore;
        let originValue = Util.operateSymbol(detailData[fieldname],",","del"); //获得原始值，移除前后逗号
        if(originValue == ids){ //如果ID相同则直接返回
            return;
        }
        let _this = this;
        let params = {
            goalId:detailKey,
            fieldname:'',  //字段名字
            fieldtype:'',  //类型
            fieldvalue:'',  //字段值
            logDelvalue:'', //日志删除值
            logAddValue:'', //日志增加值
            operateType:'', //操作类型
            doback:function(){
                    _this.doCallBack(fieldname);
            }
        };
        
        let arrId = ids.split(",");
        let data =[];
        if(arrId.length > 0 && arrId[0] != ''){
            for(let i = 0;i < arrId.length; i ++){
                data.push({id:datas[i].id,name:datas[i].name});
            }   
        }
        detailData[type] = data;
        params.fieldvalue = Util.operateSymbol(this.arrToStr(detailData[type],'id',','),",","add");//获取操作后的值，添加前后逗号
        params.logDelvalue = Util.ArrayDiffer(detailData[fieldname],params.fieldvalue,1);//删除的值
        params.logAddValue = Util.ArrayDiffer(detailData[fieldname],params.fieldvalue.split(','),2);//增加的值
        params.fieldname = fieldname;  
        detailData[fieldname] = params.fieldvalue;
        goalDetailStore.editGoalField(params);
    }

    //删除相关信息
    onLinkClick = (_id,_name,_type,_fileid,_filedname,_arrfiledname) => {
        const { goalDetailStore } = this.props;
        let {detailData,detailKey} = goalDetailStore;
        if(_type == 2){  //删除
            let params = {
                goalId:detailKey,
                fieldname:'',
                fieldtype:'',
                fieldvalue:'',
                operateType:'',
                logDelvalue:'',
                logAddValue:''
            }
            let obj = {id:_id,name:_name};
            detailData[_arrfiledname]  = Util.removeAarry(toJS(detailData[_arrfiledname]),obj);
            params.fieldvalue = this.arrToStr(detailData[_arrfiledname],'id',',');
            params.fieldname = _filedname;
            detailData[_filedname] = params.fieldvalue;
            if(_filedname == 'fileids'){
                params.fieldtype = 'del';
                params.fieldvalue = _id;
            }else{
                params.logDelvalue = _id;
            }
            goalDetailStore.editGoalField(params);
        }else if(_type == 1){
            if(_filedname == "goalids"){
                this.onNodeClick(_id);
            }
            if(_filedname == 'taskids'){
                window.location.href = '/spa/workrelate/static/index.html?#/main/workrelate/task/taskDetail?id='+_id;
            }
            if(_filedname == "fileids"){
                goalDetailStore.viewDocFiled({id:_id,relateId:detailKey,type:1,doback:function(){
                    Util.opendoc(_id);
                }});
            }
        }else{  //下载
            goalDetailStore.viewDocFiled({id:_id,relateId:detailKey,type:1,doback:function(){
                Util.downloads(_fileid);
            }});
        }
    }

    onNodeClick = (key) => {
        if (key && key != '') {
            if(typeof this.props.renderDetail == "function"){
                const { goalCommonStore:{setIsFocusFeedBack} } = this.props;
                setIsFocusFeedBack(false)
                this.props.renderDetail(key);
            }
        }
    }

    //回调函数
    doCallBack = (type) =>{
        if (typeof this.props.doCallBack === "function") {
            this.props.doCallBack(type);
        }
    }

    //数组转成字符串
    arrToStr = (arr,attribute,symbol) =>{
        let fieldvalue = symbol;
        for(let i = 0;i < arr.length;i ++){
            fieldvalue += arr[i][attribute] + symbol;
        }
        return fieldvalue;
    }

    render(){
        const {goalDetailStore} = this.props;
        const {loading,detailData,connectGoals,connectTasks} = goalDetailStore;
        return(
              <div className="wea-workrelate-relate-info">
                <div className="relate-info-top">
                    <div className="relate-info-all">
                    {this.getRelateTopInfo(this.relateTop)}                               
                    {detailData.canedit?<div className="relate-info-link">
                            <i className="icon-coms-link" />
                            {this.getUpload()}
                        </div>:<div className="relate-info-link"><i className="icon-coms-link" /><div class="wea-browser customized wea-field-readonly "><div><span class="relate-info-link-span">附件</span></div></div></div>}
                    </div>
                </div>
                {/* 相关信息显示区域 */}
                <div className="relate-info-content">  
                    {
                        this.getRelateShowInfo([
                                {type:'wrlgoal',key:'relateGoals',datas:toJS(detailData.relateGoals),fieldname:'goalids',hasdel:true,name:getLabel(330,'目标')},
                                {type:'wrltask',key:'relateTasks',datas:toJS(detailData.relateTasks),fieldname:'taskids',hasdel:true,name:getLabel(1332,'任务')},
                                {type:37,key:'relateDocs',datas:toJS(detailData.relateDocs),fieldname:'docids',hasdel:true,name:getLabel(22243,'文档')},
                                {type:152,key:'relateWorkFlows',datas:toJS(detailData.relateWorkFlows),fieldname:'wfids',hasdel:true,name:getLabel(18015,'流程')},
                                {type:7,key:'relateCutomer',datas:toJS(detailData.relateCutomer),fieldname:'crmids',hasdel:true,name:getLabel(136,'客户')},
                                {type:8,key:'relateProjects',datas:toJS(detailData.relateProjects),fieldname:'projectids',hasdel:true,name:getLabel(101,'项目')},
                                {type:0,key:'relateFileds',datas:toJS(detailData.relateFileds),fieldname:'fileids',hasdel:true,name:getLabel('156','附件')}          
                            ],1)
                    }
                    {
                        this.getRelateShowInfo([
                                {type:0,key:'connectGoals',datas:toJS(connectGoals),fieldname:'goalids',hasdel:false,name:getLabel(330,'目标')},
                                {type:'wrltask',key:'connectTasks',datas:toJS(connectTasks),fieldname:'taskids',hasdel:false,name:getLabel(1332,'任务')},
                            ],2)
                    }
                    
                </div>
            </div>
        )
    }
}